package best.driver.android.Activity.Order;


import android.app.Dialog;
import android.content.Intent;
import android.media.Rating;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.*;
import best.driver.android.*;
import best.driver.android.Activity.Base.BaseActivity;
import best.driver.android.Activity.Environment.EnvironmentActivity;
import best.driver.android.Activity.Order.Adapter.CurrentOrdersItemAdapter;
import best.driver.android.Activity.Order.Adapter.OrderItemAdapter;
import best.driver.android.Activity.Register.CheckActivity;
import best.driver.android.Activity.Register.CheckHintActivity;
import best.driver.android.Beans.*;
import best.driver.android.Event.CheckStatusEvent;
import best.driver.android.Model.OrderDetailModel;
import best.driver.android.NetBase.BackService;
import best.driver.android.Utils.GPSUtils;
import best.driver.android.Utils.ImageLoaderUtil;
import best.driver.android.Utils.Util;
import best.driver.android.View.BasePullToRefreshListView;
import best.driver.android.common.app.AppProxyFactory;
import best.driver.android.common.network.*;
import best.driver.android.common.utils.StringUtils;
import best.driver.android.manager.OrderManager;
import best.driver.android.manager.UserInfoManager;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

import java.util.ArrayList;
import java.util.List;

public class WorkActivity extends BaseActivity implements BasePullToRefreshListView.OnPullDownListener{

    long mExitTime;

    private Dialog gpsDialog;


    @InjectView(R.id.ptr_lv_my_orders)
    BasePullToRefreshListView mPrvOrders;

    @InjectView(R.id.fl_no_orders)
    FrameLayout mFlNoOrders;

    CurrentOrdersItemAdapter mAdapter;

    // //侧边栏元素start

    @InjectView(R.id.iv_head_avatar)
    ImageView mIvHeadAvatar;

    @InjectView(R.id.drawer_layout)
    DrawerLayout mDrawerLayout;

    @InjectView(R.id.drawer_list)
    LinearLayout mDrawerList;

    @InjectView(R.id.tv_name)
    TextView mDriverName;

    @InjectView(R.id.tv_phone)
    TextView mDriverPhone;

    @InjectView(R.id.star_level_rbv)
    RatingBar mRatingBarLevel;

    @InjectView(R.id.fl_off_work)
    FrameLayout mFlOffWork;

    @InjectView(R.id.btn_operation_work)
    Button mBtnOperationWork;

    @InjectView(R.id.tv_level)
    TextView mTvLevel;

    @InjectView(R.id.ll_set_environment)
    LinearLayout mLLSetEnvironment;

    @OnClick(R.id.ll_set_environment)
    protected void setEnvironment() {
        Intent intent = new Intent(this, EnvironmentActivity.class);
        startActivity(intent);
    }

    @OnClick(R.id.ll_car_detail)
    protected void jumpToCarDetail() {

        startActivity(new Intent(WorkActivity.this, CheckActivity.class));
        mDrawerLayout.closeDrawer(mDrawerList);
    }

    @OnClick(R.id.ll_my_orders)
    protected void getMyOrders() {
        if(BestApp.getInstance().getLastActivity() instanceof CheckActivity) {
            return;
        }
        startActivity(new Intent(this, OrderListActivity.class));
        mDrawerLayout.closeDrawer(mDrawerList);
    }

    @OnClick(R.id.drawer_list)
    protected void clickAll() {}


    @OnClick(R.id.btn_head_left)
    protected void showLeftMenu() {
        mDrawerLayout.openDrawer(mDrawerList);
    }

    @OnClick(R.id.ll_head)
    protected void showHead() {}

    @OnClick(R.id.btn_operation_work)
    protected void startWork() {
        mBtnOperationWork.setEnabled(false);
        if(UserInfoManager.getInstance().getAcceptOrderStatus()) {
            offWork();
        } else {
            if(showGpsDialog()) {
                mBtnOperationWork.setEnabled(true);
                return;
            }
            showWaiting();
            ApiStringRequest request = RequestFactory.createStartWorkRequest();
            request.setListener(new ApiRequest.ApiRequestListener<String>() {
                @Override
                public void onRequestSuccess(String response) {
                    mBtnOperationWork.setEnabled(true);
                    mBtnOperationWork.setText("停止接单");
                    mBtnOperationWork.setBackgroundColor(getResources().getColor(R.color.off_work_color));
                    hideWaiting();
                    Intent intent = new Intent();
                    intent.setAction(BackService.MESSAGE_ACTION);
                    sendBroadcast(intent);
                    UserInfoManager.getInstance().setAcceptOrderStatus(true);
                }

                @Override
                public void onRequestError(BestError error) {
                    mBtnOperationWork.setEnabled(true);
                    if(error instanceof BestApiError) {
                        AppInfo.showToast(WorkActivity.this, ((BestApiError) error).getErrorMessage());
                    }
                    hideWaiting();
                }
            });
            AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(request);
        }
    }


    private void offWork() {
        showWaiting();
        ApiStringRequest request = RequestFactory.createOffWorkRequest();
        request.setListener(new ApiRequest.ApiRequestListener<String>() {
            @Override
            public void onRequestSuccess(String response) {
                mBtnOperationWork.setText("开始接单");
                mBtnOperationWork.setBackgroundColor(getResources().getColor(R.color.best_red));
                mBtnOperationWork.setEnabled(true);
                UserInfoManager.getInstance().setAcceptOrderStatus(false);
                hideWaiting();
            }

            @Override
            public void onRequestError(BestError error) {
                mBtnOperationWork.setEnabled(true);
                if (error instanceof BestApiError) {
                    AppInfo.showToast(WorkActivity.this, ((BestApiError) error).getErrorMessage());
                }
                hideWaiting();
            }
        });
        AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(request);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setView(R.layout.activity_work);
        ButterKnife.inject(this, view);
        mFlOffWork.setVisibility(View.GONE);
        hideTopBar();
        mPrvOrders.setOnPullDownListener(this);
        mAdapter = new CurrentOrdersItemAdapter(this);
        mPrvOrders.setAdapter(mAdapter);
        mAdapter.setData(OrderManager.getInstance().getCurrentOrders());
        mPrvOrders.setRefreshEnabled(true);
        mDrawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View view, float v) {

            }

            @Override
            public void onDrawerOpened(View view) {
                getDriverDetail();
            }

            @Override
            public void onDrawerClosed(View view) {

            }

            @Override
            public void onDrawerStateChanged(int i) {

            }
        });
        getDriverDetail();
        showDriverView();
        if(BuildConfig.DEBUG) {
            mLLSetEnvironment.setVisibility(View.VISIBLE);
        }
        EventBus.getDefault().register(this);

    }

    private void showDriverView() {
        DriverInfo driverInfo = UserInfoManager.getInstance().getDriverInfo();
        mDriverName.setText(TextUtils.isEmpty(driverInfo.name)? "": driverInfo.name);
        mDriverPhone.setText(TextUtils.isEmpty(driverInfo.phone) ? "" : driverInfo.phone);
        mRatingBarLevel.setRating((float) driverInfo.credit);
        mTvLevel.setText(Util.getOnePointNumber(driverInfo.credit));
        if(!TextUtils.isEmpty(driverInfo.driverPhoto)) {
            ImageLoaderUtil.showImageBitmap(StringUtils.generateFileUrl(driverInfo.driverPhoto), mIvHeadAvatar, null);
        }
    }

    @Override
    public void onRefresh() {
        refreshCurrentOrders();
    }

    @Override
    public void onMore() {

    }

    @Override
    public void onResume() {
        super.onResume();
        Intent intent = new Intent();
        intent.setAction(BackService.MESSAGE_ACTION);
        sendBroadcast(intent);
        mAdapter.setData(OrderManager.getInstance().getCurrentOrders());
        refreshCurrentOrders();
        showGpsDialog();
        if(UserInfoManager.getInstance().getAcceptOrderStatus()) {
            mBtnOperationWork.setText("停止接单");
            mBtnOperationWork.setBackgroundColor(getResources().getColor(R.color.off_work_color));
        }
    }

    private boolean showGpsDialog() {
        if(!checkGps()) {
            gpsDialog.show();
            return true;
        }
        return false;
    }

    public void refreshCurrentOrders() {
        ApiObjectRequest<OrderListInfo> request = RequestFactory.createGetOrderListInfo("1", "50", true);
        request.setListener(new ApiRequest.ApiRequestListener<OrderListInfo>() {
                                @Override
                                public void onRequestSuccess(OrderListInfo response) {
                                    mPrvOrders.onRefreshComplete();
                                    if (response != null) {
                                        OrderManager.getInstance().setCurrentOrders(response.records);
                                        mAdapter.setData(OrderManager.getInstance().getCurrentOrders());
                                        mFlNoOrders.setVisibility(View.GONE);
                                        if(response.records == null || response.records.size() == 0) {
                                            mFlNoOrders.setVisibility(View.VISIBLE);
                                        }
                                    } else {
                                        mFlNoOrders.setVisibility(View.VISIBLE);
                                    }
                                }

                                @Override
                                public void onRequestError(BestError error) {
                                    mPrvOrders.onRefreshComplete();
                                }
                            }
        );
        AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(request);
    }

    private boolean checkGps() {
        if (gpsDialog != null) {
            gpsDialog.dismiss();
        }
        gpsDialog = GPSUtils.checkLocationAvailable(getActivity(), null);
        return gpsDialog == null;
    }

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            BestApp.getInstance().exit();
            super.onBackPressed();
        }
    }

    public OrderDetailModel getCurrentOrderModel(List<OrderListInfo.Records> records) {
        if(records == null || records.size() == 0)
            return null;
        OrderDetailModel model;
        for(int i = 0; i < records.size(); i++) {

        }
        return null;
    }

    private void getDriverDetail() {
        ApiObjectRequest<DriverDetail> request = RequestFactory.createGetDriverDetail();
        request.setListener(new ApiRequest.ApiRequestListener<DriverDetail>() {
            @Override
            public void onRequestSuccess(DriverDetail response) {
                view.setVisibility(View.VISIBLE);
                UserInfoManager.getInstance().setDriverInfo(response);
                if (CheckStatus.DRAFT.equals(response.auditStatus)) {

                } else if (CheckStatus.IN_AUDIT.equals(response.auditStatus)) {
                    finish();
                    startActivity(new Intent(WorkActivity.this, CheckHintActivity.class));
                } else if (CheckStatus.AUDIT_FAILURE.equals(response.auditStatus)) {
                    finish();
                    startActivity(new Intent(WorkActivity.this, CheckHintActivity.class));
                } else if (CheckStatus.AUDIT_SUCCESS.equals(response.auditStatus)) {
                    UserInfoManager.getInstance().setCheckStatus(true);
                    UserInfoManager.getInstance().setDriverInfo(response);
                }
                showDriverView();
            }

            @Override
            public void onRequestError(BestError error) {

            }
        });
        AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(request);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(CheckStatusEvent event) {
        getMyOrders();
    }

}
